package com.ruoyi.framework.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.ruoyi.common.config.OptimizationConfig;
import com.ruoyi.system.service.aggregation.impl.ProductStockServiceImpl;

/**
 * 系统启动时初始化库存到Redis
 * 
 * @author ruoyi
 * @date 2025-01-13
 */
@Component
public class StockInitListener implements ApplicationRunner
{
    @Autowired
    private ProductStockServiceImpl productStockService;
    
    @Autowired
    private OptimizationConfig optimizationConfig;
    
    @Override
    public void run(ApplicationArguments args) throws Exception
    {
        if (optimizationConfig.getStock().isCacheEnabled()) {
            System.out.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
            System.out.println("🚀 开始初始化商品库存到Redis...");
            
            try {
                // 延迟3秒，等待其他服务初始化完成
                Thread.sleep(3000);
                
                productStockService.initAllStockToRedis();
                
                System.out.println("✅ 库存初始化完成！");
                System.out.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
            } catch (Exception e) {
                System.err.println("❌ 库存初始化失败: " + e.getMessage());
                System.err.println("⚠️  系统将使用数据库库存（降级模式）");
            }
        } else {
            System.out.println("⚠️  库存缓存未启用，使用数据库库存");
        }
    }
}

